<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/controller/ctlAbstract.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busOccupation.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busAddress.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busResource.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busAvatar.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busLocation.php';
									
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/user.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/address.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/resource.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/avatar.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/generalFunctions.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/stringUtil.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/sendMail.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/simpleImage.php';
/**
 * This is the class handle the registration of new users
 */
class RegisterController extends AbstractController {
	private $_userBus;
	private $_addressBus;
	private $_resourceBus;
	private $_avatarBus;
	private $_occupationBus;
	private $_locationBus;
	/**
	 *
	 * This is the default function that will be called by the router
	 * @param array $getVars GET variables posted to index.php
	 */
	public function main(array $getVars) {
		global $ubi;
		
		$this->_userBus = new UserBus();
		$this->_addressBus = new AddressBus();
		$this->_resourceBus = new ResourceBus();
		$this->_avatarBus = new AvatarBus();
		$this->_occupationBus = new OccupationBus();
		$this->_locationBus = new LocationBus();
		
		//error list when adding user
		$errList = array();
			
		//register user
		if (isset($_POST['txtUserName']) && isset($_POST['txtPassword']) && isset($_POST['txtEmail']) 
			&& isset($_POST['selGender']) && isset($_POST['txtFirstName']) 
			&& isset($_POST['txtLastName']) && isset($_POST['txtDOB']) && isset($_POST['txtNumber']) 
			&& isset($_POST['txtStreet']) && isset($_POST['txtWard']) && isset($_POST['txtDistrict']) && isset($_POST['selCity'])) {
			$user = new UserModel();

			require_once('utility/recaptchalib.php');
			$privatekey = $ubi['SITE']['PRIVATE_KEY'];
			$resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
		
			if (!$resp->is_valid) {
			  	// What happens when the CAPTCHA was entered incorrectly
				/*die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
			         "(reCAPTCHA said: " . $resp->error . ")");*/
				$errList[] = 'Mã bảo mật không chính xác';
			} else {
				//if the code is valid
				if ($this->_userBus->isEmailExisted($_POST['txtEmail'])) {
					$errList[] = 'Email này đã có người đăng ký. Bạn hãy đăng ký với một email khác !!!';
				} else if (!$this->_userBus->isUserNameAllowed($_POST['txtUserName'])) {
					$errList[] = 'Tên đăng nhập này không hợp lệ. Bạn hãy đăng ký với một tên đăng nhập khác !!!';
				} else {
					//read address data
					$address = new AddressModel();
					$address->setDistrict($_POST['txtDistrict']);
					$address->setNumber($_POST['txtNumber']);
					$address->setStreet($_POST['txtStreet']);
					$address->setWard($_POST['txtWard']);
					$address->setCity($this->_locationBus->getLocationFromID($_POST['selCity']));
					$address->setLongitude(0);
					$address->setLatitude(0);
					$address->setType($ubi['LOCATION']['USER']);
	
					$addressID = $this->_addressBus->addAddress($address);
						
					//if insert address successfully, insert new user
					if ($addressID != 0) {
						$user->setUserName($_POST['txtUserName']);
						$user->setPasswordHash($_POST['txtPassword']);
						$user->setEmail($_POST['txtEmail']);
						$user->setFirstName($_POST['txtFirstName']);
						$user->setLastName($_POST['txtLastName']);
						$user->setDateOfBirth(GeneralFunctions::getDate($_POST['txtDOB']));
						$user->setGender($_POST['selGender']);
						$user->setEmail($_POST['txtEmail']);
						$user->setTelephone($_POST['txtPhone']);
						$user->setCellPhone($_POST['txtCellPhone']);
						$user->setOccupationID($_POST['selOccupation']);
						$user->setAddressID($addressID);
						$user->setBlast($_POST['txtBlast']);
	
						//create an activation code for user
						$activation_code = GeneralFunctions::createRandomCode();
						//						$activation_code = $this->createActivationCode();
						$user->setActivationCode($activation_code);
	
						$userID = $this->_userBus->addUser($user);
	
						if ($userID != 0) {
							if ($_FILES['img']['error'] > 0) {
								$errList[] = 'Có lỗi khi upload hình';
							} else {
								$fileName = $_FILES['img']['name'];
								if (file_exists($ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $fileName)) { //file avatar existed
									$fileName = StringUtil::changeFileName($fileName);
								}
	
								//create resource model object
								$res = new ResourceModel();
								$res->setResourceName($fileName);
								$res->setShortDescription('avatar');
	
								$fileSavedThumbnailName = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['THUMBNAIL_PATH'] . '/' . $fileName;
								$fileSavedResourceName = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $fileName;
								move_uploaded_file($_FILES['img']['tmp_name'], $fileSavedThumbnailName);
								copy($fileSavedThumbnailName, $fileSavedResourceName);
									
								//create resource bus object
								$resID = $this->_resourceBus->addResource($res);
	
								//add avatar into resource successfully
								if ($resID != 0) {
								   	$image = new SimpleImage();
								   	$image->load($fileSavedThumbnailName);
								   	$image->resize($ubi['SITE']['WIDTH_THUMBNAIL'], $ubi['SITE']['HEIGHT_THUMBNAIL']);
								   	$image->save($fileSavedThumbnailName);
								   	
								   	$image->load($fileSavedResourceName);
								   	$image->resize($ubi['SITE']['WIDTH_RESOURCE'], $ubi['SITE']['HEIGHT_RESOURCE']);
								   	$image->save($fileSavedResourceName);
									
									$avatar = new AvatarModel();
									$avatar->setUserID($userID);
									$avatar->setResourceID($resID);
										
									$this->_avatarBus->addAvatar($avatar);
								} else {
									$errList[] = "Không upload avatar được.";
								}
							}
								
							$notice = "RegisterSuccessfully";
							include $ubi['SERVER']['SERVER_ROOT'] .  '/view/viewNotice.php';
								
							//send email to the user with activation code
							SendMail::getEmailTemplate($ubi['EMAIL']['REGISTER'], $template, $subject);
				
							$arrParam = array();
							$arrParam[] = $user->getFirstName() . ' ' . $user->getLastName();	
							$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . '">' . $ubi['SERVER']['SITE_NAME'] . '</a>';
							$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . 'index.php?Activate&code=' . $activation_code . '">kích hoạt</a>';
							$arrParam[] = $ubi['SERVER']['SITE_ROOT'] . 'index.php?Activate&code=' . $activation_code;
							$arrParam[] = $user->getUserName();
							$arrParam[] = $user->getPasswordHash();
							$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . '">' . $ubi['SERVER']['SITE_NAME'] . '</a>';
							
							SendMail::sendEMail($template, $subject, $arrParam, $user->getEmail());
							return;
						} else {
							$errList[] = 'Có lỗi xảy ra khi thêm user vào CSDL';
							//include $ubi['SERVER']['SERVER_ROOT'] .  '/view/viewRegister.php';
						}
					} else {
						$errList[] = 'Có lỗi xảy ra khi thêm địa chỉ vào CSDL';
						$this->_addressBus->deleteAddress($addressID);
					}
				}
			}
		}
		//get list of occupations
		$occupationList = $this->_occupationBus->getOccupationList();
				
		include $ubi['SERVER']['SERVER_ROOT'] .  '/view/viewRegister.php';
	}
	
	/**
	 * 
	 * This function is used to create Activation Code according to current time 
	 * @param $username username of the user that we want to create activation code for
	 */
	protected function createActivationCode() {
		//begin of method createActivationCode		
		//get the unix current time
		$time = time();
		
		//declare the code variable to hold the code that will be created
		$code = "";
		
		//iterate through each character in $username
		for ($i = 0; $i < 20 - strlen($time); $i++) {
		//begin of for $i
			
			//get the random value from mt_rand
			//the value will be from 0 to 35
			$rvalue = mt_rand(0, 35);
			
			//if the value in the range of 0 to 25, we will convert it to alphabet character
			//by adding 97 to its ascii code
			//if the value is greater than 25, we will convert it to numeric character
			//by adding 22 to its ascii code
			if ($rvalue < 26){
				$code .= chr($rvalue + 97);
			} else {
				$code .= chr($rvalue + 22);
			}			
		}//end of for $i
		
		//add the unix time to the code
		$code .= $time;
		
		return $code;
	}//end of method createActivationCode
}
?>